import time
import os

HOSTAPD_CONF = "/etc/hostapd/hostapd.conf"
LEASES_FILE = "/var/lib/misc/dnsmasq.leases"

def read_hostapd_config():
    config = {}
    with open(HOSTAPD_CONF, 'r') as f:
        for line in f:
            if '=' in line and not line.startswith('#'):
                key, value = line.strip().split('=', 1)
                config[key] = value
    return config

def update_hostapd_config(updates):
    lines = []
    with open(HOSTAPD_CONF, 'r') as f:
        for line in f:
            if '=' in line and not line.startswith('#'):
                key = line.split('=')[0]
                if key in updates:
                    line = f"{key}={updates[key]}\n"
                    updates.pop(key)
            lines.append(line)
    for key, val in updates.items():
        lines.append(f"{key}={val}\n")
    with open(HOSTAPD_CONF, 'w') as f:
        f.writelines(lines)

def get_connected_clients():
    clients = []
    try:
        current_time = int(time.time())
        with open(LEASES_FILE, 'r') as f:
            for line in f:
                parts = line.strip().split()
                if len(parts) >= 5:
                    lease_expiry = int(parts[0])
                    if lease_expiry > current_time:
                        timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lease_expiry))
                        clients.append({
                            "mac": parts[1],
                            "ip": parts[2],
                            "hostname": parts[3],
                            "time": timestamp
                        })
    except FileNotFoundError:
        pass
    return clients
